package top.codedance.iotp.client.manage.net.handler.taskHandler;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.manage.ManageApplication;
import top.codedance.iotp.client.manage.net.listenner.TaskExecuter;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;

public class LoadExecuterImpl implements TaskExecuter {
    private static Logger logger = ManageApplication.getLogger(DownloadExecuterImpl.class);

    @Override
    public void exec(ChannelHandlerContext channelHandlerContext, byte[] data, String taskId) {
        try {
            String str = new String(data, StandardCharsets.UTF_8);
            JSONObject jo = JSON.parseObject(str);
            Double cpu = jo.getDouble("cpu");
            if(cpu != null) {
                ManageApplication.loadRequestCount = 0;
                if (cpu >= ManageApplication.cpuRate) {
                    ManageApplication.p.destroyForcibly();
                    ManageApplication.clientFuture.cancel(true);
                    logger.debug("Client use cpu : >= 60%, Kill this client.");
                }
                logger.debug("Client use cpu : " + cpu + "%.");
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
    }
}
